package com.ruoyi.fun.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.fun.domain.EcLogistics;
import com.ruoyi.fun.domain.EcLogisticsCompany;
import com.ruoyi.fun.domain.EcOrder;
import com.ruoyi.fun.mapper.EcLogisticsCompanyMapper;
import com.ruoyi.fun.mapper.EcLogisticsMapper;
import com.ruoyi.fun.mapper.EcOrderMapper;
import com.ruoyi.fun.service.ILogisticsTrackingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物流跟踪服务实现类
 *
 * @author ruoyi
 */
@Service
public class LogisticsTrackingServiceImpl implements ILogisticsTrackingService {

    private static final Logger log = LoggerFactory.getLogger(LogisticsTrackingServiceImpl.class);

    @Autowired
    private EcOrderMapper ecOrderMapper;

    @Autowired
    private EcLogisticsMapper ecLogisticsMapper;

    @Autowired
    private EcLogisticsCompanyMapper ecLogisticsCompanyMapper;

    private RestTemplate restTemplate;

    public LogisticsTrackingServiceImpl() {
        this.restTemplate = new RestTemplate();
    }

    // ShowAPI的AppKey
    private static final String APP_KEY = "5862275327914C42aDdBb25141a1cC16";

    // ShowAPI物流查询接口地址
    private static final String API_URL = "https://route.showapi.com/2650-8?appKey=" + APP_KEY;

    @Override
    public AjaxResult getLogisticsTrackingByOrderNo(String orderNo) {
        try {
            // 根据订单号查询订单信息
            EcOrder queryOrder = new EcOrder();
            queryOrder.setOrderNo(orderNo);
            List<EcOrder> orderList = ecOrderMapper.selectEcOrderList(queryOrder);
            if (orderList == null || orderList.isEmpty()) {
                log.error("订单不存在：{}", orderNo);
                return AjaxResult.error("订单不存在");
            }
            EcOrder order = orderList.get(0);

            // 2. 根据订单号查询物流信息
            EcLogistics logistics = ecLogisticsMapper.selectEcLogisticsByOrderNo(orderNo);
            if (logistics == null || logistics.getLogisticsNo() == null) {
                log.error("物流信息不存在：{}", orderNo);
                return AjaxResult.error("物流信息不存在");
            }


            // 3. 获取收件人手机号后四位
            String receiverPhone = order.getReceiverPhone();
            String phone = "";
            if (receiverPhone != null && receiverPhone.length() >= 4) {
                phone = receiverPhone.substring(receiverPhone.length() - 4);
            }


            // 4. 获取快递公司简称
            String logisticsCompany = String.valueOf(logistics.getLogisticsCompany());
            String companyCode = getCompanyCode(logisticsCompany);

            // 5. 调用外部API获取物流跟踪信息
            return callExternalLogisticsApi(companyCode, logistics.getLogisticsNo(), phone);

        } catch (Exception e) {
            log.error("获取物流跟踪信息失败：{}", e.getMessage(), e);
            return AjaxResult.error("获取物流跟踪信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据快递公司ID获取对应的简称代码
     * @param companyIdStr 快递公司ID
     * @return 快递公司简称代码
     */
    private String getCompanyCode(String companyIdStr) {
        try {
            // 将字符串ID转换为Long类型
            Long companyId = Long.parseLong(companyIdStr);
            
            // 从数据库根据ID查询快递公司简称
            String companyCode = ecLogisticsCompanyMapper.selectComById(companyId);
            
            if (companyCode != null && !companyCode.trim().isEmpty()) {
                log.info("从数据库获取到快递公司简称：ID {} -> {}", companyId, companyCode);
                return companyCode;
            } else {
                log.warn("数据库中未找到ID为{}的快递公司，使用默认值", companyId);
                return "unknown";
            }
        } catch (NumberFormatException e) {
            log.error("快递公司ID格式错误：{}", companyIdStr, e);
            return "unknown";
        } catch (Exception e) {
            log.error("查询快递公司简称时发生异常：{}", e.getMessage(), e);
            return "unknown";
        }
    }

    @Override
    public AjaxResult callExternalLogisticsApi(String com, String nu, String phone) {
        try {
            // 构建表单参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("com", com);
            params.add("nu", nu);
            params.add("phone", phone);

            // 设置请求头为表单格式
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 创建请求实体
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);



            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    API_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            String responseBody = response.getBody();

            // 解析响应
            if (responseBody != null) {
                JSONObject jsonResponse = JSON.parseObject(responseBody);
                
                // 检查API调用是否成功
                Integer showapiResCode = jsonResponse.getInteger("showapi_res_code");
                if (showapiResCode != null && showapiResCode == 0) {
                    // API调用成功，返回物流跟踪数据
                    JSONObject showapiResBody = jsonResponse.getJSONObject("showapi_res_body");
                    return AjaxResult.success("获取物流跟踪信息成功", showapiResBody);
                } else {
                    // API调用失败
                    String errorMsg = jsonResponse.getString("showapi_res_error");
                    log.error("物流查询API调用失败：{}", errorMsg);
                    return AjaxResult.error("物流查询失败：" + errorMsg);
                }
            } else {
                log.error("物流查询API响应为空");
                return AjaxResult.error("物流查询API响应为空");
            }

        } catch (Exception e) {
            log.error("调用物流查询API异常：{}", e.getMessage(), e);
            return AjaxResult.error("调用物流查询API异常：" + e.getMessage());
        }
    }
}